
#include "IO.h"
#include "BSP_Config.h"

#if (BSP_BUZZER_TYPE == BSP_PWM_BUZZER_ENABLE)

#define BUZ_S_ON	1
#define BUZ_S_OFF	0


static const IO_T Buzzer =
{
    (void*)BUZ_GP, BUZ_PIN
};

static uint8_t buzzerState;
	
/**
    \brief      configure the GPIO ports
    \param[in]  none
    \param[out] none
    \retval     none
  */
static void BSP_Buzzer_IO_Init(void)
{
	IO_Init(&Buzzer, IO_Mode_OUT);
}


void TIMER1_IRQHandler(void)
{
    if(SET == timer_interrupt_flag_get(BUZ_TIMER, TIMER_INT_UP)){
        timer_interrupt_flag_clear(BUZ_TIMER, TIMER_INT_UP);
		
		IO_Set(&Buzzer, ! IO_Get(&Buzzer));
    }
}


/**
    \brief      configure the TIMER peripheral
    \param[in]  none
    \param[out] none
    \retval     none
  */
void BSP_Buzzer_Timer_Init(void)
{
    timer_parameter_struct timer_initpara;

	uint32_t clock = rcu_clock_freq_get(CK_APB1)/4;
	uint32_t period = clock / 4000u - 1;
	
    rcu_periph_clock_enable(RCU_TIMER1);

    timer_deinit(BUZ_TIMER);

    /* TIMER1 configuration */
    timer_initpara.prescaler         = 3;
    timer_initpara.alignedmode       = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection  = TIMER_COUNTER_UP;
    timer_initpara.period            = period;
    timer_initpara.clockdivision     = TIMER_CKDIV_DIV1;
    timer_initpara.repetitioncounter = 0;
    timer_init(BUZ_TIMER,&timer_initpara);
	
	
	timer_auto_reload_shadow_disable(BUZ_TIMER);
//		timer_interrupt_flag_clear(BUZ_TIMER, TIMER_INT_UP);
//	    timer_interrupt_enable(BUZ_TIMER, TIMER_INT_UP);
	nvic_irq_enable(TIMER1_IRQn, 2, 0);
    /* auto-reload preload enable */
//	    timer_enable(BUZ_TIMER);
}


void BSP_Buzzer_Set(uint8_t state){
	if(buzzerState == state){
		return ;
	}
	if(state){
	    timer_enable(BUZ_TIMER);
		timer_interrupt_enable(BUZ_TIMER, TIMER_INT_UP);
		IO_Set(&Buzzer, BUZ_S_ON);
	}
	else{
		timer_interrupt_disable(BUZ_TIMER, TIMER_INT_UP);
	    timer_disable(BUZ_TIMER);
		timer_interrupt_flag_clear(BUZ_TIMER, TIMER_INT_UP);
		IO_Set(&Buzzer, BUZ_S_OFF);
	}
	buzzerState = state;
}

uint8_t BSP_Buzzer_State(void){
	return buzzerState;
}

void BSP_Buzzer_Init(void)
{
	BSP_Buzzer_IO_Init();
	BSP_Buzzer_Timer_Init();
	BSP_Buzzer_Set(0);
}

#endif 


